package com.rankeiot.dev;


import com.jfinal.template.Engine;
import com.jfinal.template.Template;

import com.rankeiot.core.Module;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.SqlToyContext;
import org.sagacity.sqltoy.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@ConditionalOnProperty(name="active",havingValue = "dev",prefix = "spring.profiles")
@Configuration
@ComponentScan(basePackages = {"com.rankeiot.dev.service","com.rankeiot.dev.controller"})
@Slf4j
public class EasyDevPlugin implements Module {
    //private static Engine engine = Engine.create("VuePageEngine");

    @Autowired
    CacheManager cacheManager;


    @EventListener
    public void onEnvironmentPrepared(ApplicationReadyEvent ape){
        DevConfig.basePackage = ape.getSpringApplication().getMainApplicationClass().getPackage().getName();
        DevConfig.basePath = ape.getSpringApplication().getMainApplicationClass().getClassLoader().getResource("./").getPath()
                .replaceFirst("target/test-classes/", "")
                .replaceFirst("target/classes/", "");
    }
    @EventListener
    public void onRefresh(ContextRefreshedEvent e){

        try {
            //清理Sqltoy的反射缓存
            Field field = BeanUtil.class.getDeclaredField("getMethods");
            field.setAccessible(true);
            Map m= (Map)field.get(BeanUtil.class);
            m.clear();

            field = BeanUtil.class.getDeclaredField("setMethods");
            field.setAccessible(true);
            m= (Map)field.get(BeanUtil.class);
            m.clear();

            field = BeanUtil.class.getDeclaredField("cascadeModels");
            field.setAccessible(true);
            m= (Map)field.get(BeanUtil.class);
            m.clear();

        } catch (NoSuchFieldException ex) {
            throw new RuntimeException(ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
        if(cacheManager!=null){
            for(String name:cacheManager.getCacheNames()){
                cacheManager.getCache(name).clear();
            }
        }

    }
    @Override
    public void start(ApplicationContext context) {
        regMenu(DevMenu.class);


       // engine.setToClassPathSourceFactory();
       // Template template=engine.getTemplate("/vue_render.html");
        //4.切换代理（让静态文件优先）
        /**
        HandlerPipeline pipeline = new HandlerPipeline();
        pipeline.next(ctx -> {
            if(ctx.getHandled()){
                return;
            }
            if(ctx.getRendered()){
                return;
            }
            if(Objects.equals(ctx.method(),"GET")) {
                if (ctx.path().endsWith(".vue")) {
                    if (ctx.accept().indexOf("html") > 1) {
                        //找资源
                        URL uri = StaticMappings.find(ctx.path());
                        if (uri != null) {
                            ctx.contentType("text/html;charset=utf8");
                            URLConnection connection = uri.openConnection();
                            connection.setUseCaches(false);

                            try (InputStream stream = connection.getInputStream()) {
                                String text = StringUtil.read(stream);
                                String data= Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
                                Map<String,Object> param=new HashMap<>();
                                param.put("data",data);
                                param.put("title",ctx.path());
                                param.put("path",ctx.path());
                                template.render(param,ctx.outputStream());
                                //System.out.println(data);
                                ctx.setHandled(true);
                            }
                        }
                    }
                }
            }
        }).next(Solon.app().handlerGet());
        Solon.app().handlerSet(pipeline);
**/
//        app.add("**.vue", MethodType.GET, ctx -> {
//            System.out.println(ctx.accept());
//        });

    }

}
